<template>
  <div style="height: 100%" >
    <a-layout class="container">
      <a-layout>
        <a-layout-content id="conten-box" class="content">

          <flow-area
            ref="flowArea"
            :browser-type="browserType"
            :current-tool="currentTool"
            :drag-info="dragInfo"
            :flow-config="flowConfig"
            :flow-data="flowData"
            :plumb="plumb"
            @NodeStart="initFlow"
            :select-group.sync="currentSelectGroup"
            :select.sync="currentSelect"
            @openWin="openWin"
            @findNodeConfig="findNodeConfig"
            @getShortcut="getShortcut"
            @saveFlow="saveFlow"
            @selectTool="selectTool"
            @nodeInfo="nodeInfo"
            @deleteNode="deleteNode"
            @leftClickSelectNode="leftClickSelectNode"
          />
          <vue-context-menu :context-menu-data="linkContextMenuData" @deleteLink="deleteLink" @viewLink="viewLink" />
        </a-layout-content>

        <a-layout-sider class="content-right">
          <operating-data ref="operatingData" />
        </a-layout-sider>

      </a-layout>
    </a-layout>
    <!-- 生成拓扑图片 -->
    <a-modal
      :closable="flowPicture.closable"
      :mask-closable="flowPicture.maskClosable"
      :title="'流程设计图_' + flowData.attr.id + '.png'"
      :visible="flowPicture.modalVisible"
      cancel-text="取消"
      centered
      ok-text="下载到本地"
      width="90%"
      @cancel="cancelDownLoadFlowPicture"
      @ok="downLoadFlowPicture"
    >
      <img :src="flowPicture.url" style="width: 100%" />
    </a-modal>
    <!-- 设置 -->
    <setting-modal ref="settingModal" :flow-config="flowConfig" />
    <!-- 快捷键大全 -->
    <shortcut-modal ref="shortcutModal" />
    <!-- 测试 -->
    <test-modal ref="testModal" :flow-config="flowConfig" @loadFlow="loadFlow" />
    <!-- <a-drawer
      :visible="visible"
      :z-index="99999999"
      placement="right"
      title="端口"
      width="490"
      :maskClosable="false"
      @close="onClose"
    >
      <indexA
        v-if="visible"
        style="height: calc(100vh - 136px)"
        :deviceId="deviceId"
        @handleLigature="handlePortId"
      />

      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          关闭
        </a-button>
      </div>
    </a-drawer>-->
  </div>
</template>

<script>
import '@/components/flow-design/assets/style/index.less'
import { jsPlumb } from 'jsplumb'
import cloneDeep from 'lodash/cloneDeep'
import { tools } from './config/tools.js'
import {
  commonNodes,
  commonNodes1,
  commonNodes2,
  commonNodes3,
  commonNodes4,
  commonNodes5,
  highNodes,
  laneNodes,
} from './config/nodes.js'
import { flowConfig as defaultFlowConfig, flowStatus, settingConfig } from './config/flow 2.js'
import { shortcutKeys } from './config/shortcutKeys.js'
import { linkMenu } from './config/contextMenu.js'
import html2canvas from 'html2canvas'
import canvg from 'canvg'
import { getBrowserType, setFlowConfig, utils } from './utils/common.js'
import operatingData from './modules/operating-data'
import FlowArea from './modules/FlowArea-view'
import FlowAttr from './modules/FlowAttr-view'
import SettingModal from './modules/SettingModal'
import ShortcutModal from './modules/ShortcutModal'
import TestModal from './modules/TestModal'
import NodeList from './modules/NodeList'
import indexA from './Indexa.vue'
import { getAction, httpAction, deleteAction } from '@/api/manage'

export default {
  name: 'Design',
  components: {
    html2canvas,
    canvg,
    FlowArea,
    FlowAttr,
    SettingModal,
    ShortcutModal,
    TestModal,
    NodeList,
    indexA,
    operatingData,
  },
  props: {
    //表单禁用
    flowChartData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      infoList: [],
      visible: false,
      flowConfig: cloneDeep(defaultFlowConfig),
      info: {
        version: '1.0.0',
        author: '',
        gitee: '',
      },
      activeKey:'1',
      deviceData:{
        id:'FPS_ZH_01',
        status:'同步',
        status1:"未同步",
        wML:'0.00000001',
        wML1:'0.00000001',

      },
      browserType: 3,
      plumb: {},
      field: {
        tools: tools,
        commonNodes: commonNodes,
        commonNodes1: commonNodes1,
        commonNodes2: commonNodes2,
        commonNodes3: commonNodes3,
        commonNodes4: commonNodes4,
        commonNodes5: commonNodes5,
        highNodes: highNodes,
        laneNodes: laneNodes,
      },
      flowData: {
        nodeList: [],
        linkList: [],
        attr: {
          id: '',
        },
        config: {
          showGrid: false,
          showGridText: '隐藏网格',
          showGridIcon: 'eye',
        },
        status: flowStatus.CREATE,
        remarks: [],
      },
      currentTool: {
        type: 'drag',
        icon: 'drag',
        name: '拖拽',
      },
      areaName: true,
      currentSelect: {},
      currentSelectGroup: [],
      activeShortcut: true, // 画布聚焦开启快捷键
      linkContextMenuData: linkMenu,
      flowPicture: {
        url: '',
        modalVisible: false,
        closable: false,
        maskClosable: false,
      },
      dragInfo: {
        type: '',
        belongTo: '',
      },
      topologyList: [],
      url: {
        list: '/topology/topologyVmDevice/queryTopologyVmDeviceTypeList',
        find: '/topology/getTopology',
        // find: '/topology/topologyInstantiateAdmin/queryInstantiateChart',
        saveNode: '/topology/topologyInstantiateAdmin/saveInstantiateNode',
        saveLine: '/topology/topologyInstantiateAdmin/saveInstantiateLink',
        deleteNode: '/topologyInst/dmTopologyInst/delete', //删除设备接口
        deleteLine: '/topologyInstLine/dmTopologyInstLine/delete',
      },
      deviceId: {
        sourceDeviceId: '',
        targetDeviceId: '',
        devSourId: '',
        devTargId: '',
        id: '',
        isshow: false,
        portObj: {},
        arrt: '',
      },
      valObj: {},
    }
  },
  created() {
    this.topologyTree()
  },
  mounted() {
    // 浏览器兼容性
    this.dealCompatibility()
    // 实例化JsPlumb
    this.initJsPlumb()
    // 初始化快捷键
    this.listenShortcut()
    // 初始画布设置
    this.initSettingConfig()
    // 初始化拓扑图
    this.initFlow()
  },
  methods: {
    // 删除节点事件
    deleteNode(val) {
      const newNode = {
        id: val.id,
      }
      console.log(val, 'shan11chu节点')
      deleteAction(this.url.deleteNode, newNode).then((res) => {
        if (res.success) {
          this.$message.success('删除节点成功')
        }
      })
    },
    // 将选中的端口连线保存
    handlePortId(val) {
      this.valObj = val
    },
    async topologyTree() {
      let resultlist = [
        {
          vmDeviceTypeId: '1666682659826425857',
          vmDeviceCategory: '交换机',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1666688011510865922',
              vmDeviceName: '馈电基带',
            },
          ],
        },
        {
          vmDeviceTypeId: '1666682744425537538',
          vmDeviceCategory: '路由器',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1666688172597305346',
              vmDeviceName: '协议网关',
            },
          ],
        },
        {
          vmDeviceTypeId: '1666682835857170434',
          vmDeviceCategory: '客户端',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1666688317829275649',
              vmDeviceName: 'V频段上变频器',
            },
          ],
        },
        {
          vmDeviceTypeId: '1666682869059280897',
          vmDeviceCategory: '实体设备',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1667049644824809474',
              vmDeviceName: 'Q频段下变频器',
            },
          ],
        },
        {
          vmDeviceTypeId: '1668176201354125313',
          vmDeviceCategory: '321',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1667746084362395649',
              vmDeviceName: '单通道下变频器',
            },
          ],
        },
        {
          vmDeviceTypeId: '1666688568510242817',
          vmDeviceCategory: '3212',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1667064273336610818',
              vmDeviceName: '中频开关矩阵',
            },
          ],
        },
        {
          vmDeviceTypeId: '166668837355899289715',
          vmDeviceCategory: '3212244',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1666688514634407937',
              vmDeviceName: '测控基带',
            },
          ],
        },
        // {
        //   vmDeviceTypeId: '1666688373558992898',
        //   vmDeviceCategory: '3212233',
        //   topologyVmDeviceVOList: [
        //     {
        //       vmDeviceId: '166663885146344079372',
        //       vmDeviceName: '前端控制设备',
        //     },
        //   ],
        // },
        {
          vmDeviceTypeId: '1666688373558992899',
          vmDeviceCategory: '3212222',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '1666682851463440793735',
              vmDeviceName: 'B码产生设备',
            },
          ],
        },
        {
          vmDeviceTypeId: '16666883735589928911',
          vmDeviceCategory: '3212212',
          topologyVmDeviceVOList: [
            {
              vmDeviceId: '166668851463440792243735',
              vmDeviceName: '喇叭天线',
            },
          ],
        },
        // {
        //   vmDeviceTypeId: '16666883735589928912',
        //   vmDeviceCategory: '321221',
        //   topologyVmDeviceVOList: [
        //     {
        //       vmDeviceId: '16666885146344079224311735',
        //       vmDeviceName: '入网认证中心控制子系统',
        //     },
        //   ],
        // },
      ]
      this.topologyList = resultlist.map((ik) => {
        ik.list = ik.topologyVmDeviceVOList.map((item) => {
          return {
            type: commonNodes.find((pre) => {
              return pre.nodeName === item.vmDeviceName
            }).type,
            nodeName: item.vmDeviceName,
            icon: commonNodes.find((pre) => {
              return pre.nodeName === item.vmDeviceName
            }).icon,
            vmDeviceId: item.vmDeviceId,
          }
        })
        return ik
      })
      console.log(this.topologyList, 111)
    },
    // async topologyTree() {
    //   return new Promise((resolve, reject) => {
    //     getAction(this.url.list, {}).then(response => {
    //       console.log("----cas 登录--------", response.result);
    //       if (response.success) {
    //         this.topologyList = response.result.map(ik => {
    //           ik.list = ik.topologyVmDeviceVOList.map(item => {
    //             return {
    //               type: commonNodes.find((pre) => {
    //                 return pre.nodeName === item.vmDeviceName
    //               }).type,
    //               nodeName: item.vmDeviceName,
    //               icon: commonNodes.find((pre) => {
    //                 return pre.nodeName === item.vmDeviceName
    //               }).icon,
    //               vmDeviceId: item.vmDeviceId
    //             }
    //           })
    //           return ik
    //         })

    //         resolve(response)
    //       } else {
    //         resolve(response)
    //       }
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    //保存端口并且保存连线
    savePortSure() {
      if (this.deviceId.isshow) {
        this.visible = false
      } else {
        if (this.valObj.id) {
          const lineObj = {
            cls: {
              linkColor: '#2a2929',
              linkThickness: 2,
              linkType: 'Straight',
            },
            id: this.valObj.deviceId,
            label: '',
            type: 'link',
            topologyId: this.flowChartData.id,
            instaId: this.flowChartData.id,
            sourceId: this.valObj.sourceDeviceId,
            targetId: this.valObj.targetDeviceId,
            sourceDevicePort: this.valObj.sourceId,
            targetDevicePort: this.valObj.targetId,
            sourceDeviceId: this.valObj.devSourId,
            targetDeviceId: this.valObj.devTargId,
          }
          httpAction(this.url.saveLine, lineObj, 'post').then((res) => {
            if (res.success) {
              this.$message.success('连线成功')
              this.visible = false
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.$message.error('请连接端口')
        }
      }
    },
    // 取消端口并取消设备连线
    onClose() {
      // if (!this.deviceId.isshow) {
      //   this.plumb.deleteConnection(
      //     this.plumb.getConnections({
      //       source: this.deviceId.sourceDeviceId,
      //       target: this.deviceId.targetDeviceId
      //     })[0]
      //   )
      //   const linkList = this.flowData.linkList
      //   linkList.splice(
      //     linkList.findIndex(
      //       link => link.sourceId === this.valObj.sourceDeviceId && link.targetId === this.valObj.targetDeviceId
      //     ),
      //     1
      //   )
      //   this.valObj = {}
      // }

      this.visible = false
    },
    // 初始画布设置
    initSettingConfig() {
      if (!this.$ls.get('settingConfig')) {
        this.$ls.set('settingConfig', settingConfig)
      } else {
        this.flowConfig = setFlowConfig(this.flowConfig, this.$ls.get('settingConfig'))
      }
    },
    //左键选中一个设备，展示该设备的信息
    leftClickSelectNode(val) {
      console.log(val, '左键的节点是啥')
      // this.$set()
      this.$refs.operatingData.selectDevice = val.id
      this.$refs.operatingData.handleChange(val.id)
    },
    // 设置dragInfo
    setDragInfo(info) {
      this.dragInfo = info
    },
    // 浏览器兼容性
    dealCompatibility() {
      this.browserType = getBrowserType()
      if (this.browserType === 2) {
        shortcutKeys.scaleContainer = {
          code: 16,
          codeName: 'SHIFT(chrome下为ALT)',
          shortcutName: '画布缩放',
        }
      }
    },
    // 实例化JsPlumb
    initJsPlumb() {
      this.plumb = jsPlumb.getInstance(this.flowConfig.jsPlumbInsConfig)

      this.plumb.bind('beforeDrop', (info) => {
        const sourceId = info.sourceId
        const targetId = info.targetId

        if (sourceId === targetId) return false
        const hasMultipleLine = this.flowData.linkList.find(
          (link) => link.sourceId === sourceId && link.targetId === targetId
        )

        if (hasMultipleLine) {
          this.$message.error('同方向的两节点连线只能有一条！')
          return false
        }
        return true
      })

      this.plumb.bind('connection', (conn) => {
        const connObj = conn.connection.canvas
        const o = {}
        let id
        let label
        if (this.flowData.status === flowStatus.CREATE || this.flowData.status === flowStatus.MODIFY) {
          id = 'link-' + utils.getId()
          label = ''
        } else if (this.flowData.status === flowStatus.LOADING) {
          const l = this.flowData.linkList[this.flowData.linkList.length - 1]
          id = l.id
          label = l.label
        }
        connObj.id = id
        o.type = 'link'
        o.id = id
        o.sourceId = conn.sourceId
        o.targetId = conn.targetId
        o.label = label
        o.cls = {
          linkType: this.flowConfig.jsPlumbInsConfig.Connector[0],
          linkColor: this.flowConfig.jsPlumbInsConfig.PaintStyle.stroke,
          linkThickness: this.flowConfig.jsPlumbInsConfig.PaintStyle.strokeWidth,
        }
        document.querySelector('#' + id).addEventListener('contextmenu', (e) => {
          this.showLinkContextMenu(e)
          this.currentSelect = this.flowData.linkList.find((l) => l.id === id)
        })

        document.querySelector('#' + id).addEventListener('click', (e) => {
          const event = window.event || e
          event.stopPropagation()
          this.currentSelect = this.flowData.linkList.find((l) => l.id === id)
        })

        if (this.flowData.status !== flowStatus.LOADING) {
          this.flowData.linkList.push(o)
        }
        this.deviceId.sourceDeviceId = o.sourceId
        this.deviceId.targetDeviceId = o.targetId
        this.deviceId.devSourId = this.flowData.nodeList.find((item) => item.id === conn.sourceId).deviceId
        this.deviceId.devTargId = this.flowData.nodeList.find((item) => item.id === conn.targetId).deviceId
        this.deviceId.id = o.id
        this.deviceId.topologyId = this.flowChartData.id
        this.deviceId.portObj = {}
        this.deviceId.isshow = false
        this.visible = true
      })

      this.plumb.importDefaults({
        ConnectionsDetachable: this.flowConfig.jsPlumbConfig.conn.isDetachable,
      })
    },
    // 初始化快捷键
    listenShortcut() {
      document.onkeydown = (e) => {
        const event = window.event || e

        // 画布聚焦开启快捷键
        if (!this.activeShortcut) return
        const key = event.key

        switch (key) {
          case shortcutKeys.multiple.code:
            this.$refs.flowArea.rectangleMultiple.flag = true
            break
          case shortcutKeys.dragContainer.code:
            this.$refs.flowArea.container.dragFlag = true
            break
          case shortcutKeys.dragTool.code:
            this.selectTool('drag')
            break
          case shortcutKeys.connTool.code:
            this.selectTool('connection')
            break
          case shortcutKeys.leftMove.code:
            this.moveNode('left')
            break
          case shortcutKeys.upMove.code:
            this.moveNode('up')
            break
          case shortcutKeys.rightMove.code:
            this.moveNode('right')
            break
          case shortcutKeys.downMove.code:
            this.moveNode('down')
            break
        }

        if (event.ctrlKey) {
          switch (key) {
            case shortcutKeys.settingModal.code:
              this.saveFlow()
              break
            case shortcutKeys.testModal.code:
              this.openTest()
              break
          }
        }
      }
      // 拖拽、缩放、多选快捷键复位
      document.onkeyup = (e) => {
        const event = window.event || e

        const key = event.key
        if (key === shortcutKeys.dragContainer.code) {
          this.$refs.flowArea.container.dragFlag = false
        } else if (key === shortcutKeys.multiple.code) {
          this.$refs.flowArea.rectangleMultiple.flag = false
        }
      }
    },
    // 初始化拓扑图
    initFlow() {
      if (this.flowChartData.id) {
        this.flowData.status = flowStatus.MODIFY
      }
      if (this.flowData.status === flowStatus.CREATE) {
        this.flowData.attr.id = 'flow-' + utils.getId()
      } else {
        // let data = {
        //   'nodeList': [
        //     { 'type': 'ProtocolGateway', 'nodeName': 'S5700', 'icon': 'udpOdd', 'name': '1', 'id': 'commons-7461209e83c24d19af38b1971e8186f0', 'height': 50, 'x': 4010, 'width': 120, 'y': 4045 },
        //     { 'type': 'ProtocolGateway', 'nodeName': 'NE40', 'icon': 'udpOdd', 'name': '3', 'id': 'common-16c94d76829f4c9aafdeb97f50a2fb2a', 'height': 50, 'x': 4010, 'width': 120, 'y': 4135 },
        //     { 'type': 'ProtocolGateway', 'nodeName': 'USG5500', 'icon': 'udpOdd', 'name': '3', 'id': 'commonu-5ec18c20b3744b5086d38a65f4bfbea1', 'height': 50, 'x': 4010, 'width': 120, 'y': 4225 },
        //     { 'type': 'ProtocolGateway', 'nodeName': 'tcp客户端', 'icon': 'udpOdd', 'name': '4', 'id': 'commona-91f8aefebdb540f2ad41f190a985a536', 'height': 50, 'x': 4045, 'width': 120, 'y': 4315 },
        //     { 'type': 'VBandUpconverter', 'nodeName': 'S5700', 'icon': 'tcpK', 'name': '3', 'id': 'commons-4e140b0f33714b98869d6f296b447df3', 'height': 50, 'x': 4185, 'width': 120, 'y': 4225 },
        //     { 'type': 'VBandUpconverter', 'nodeName': 'NE40', 'icon': 'tcpK', 'name': '4', 'id': 'common-978d120e27ab49f185bffb9c242451a1', 'height': 50, 'x': 4185, 'width': 120, 'y': 4320 },
        //     { 'type': 'commVBandUpconverteronu', 'nodeName': 'USG5500', 'tcpK': 'port', 'name': '2', 'id': 'commonu-209ed52054df4e1a8da7d2042a493033', 'height': 50, 'x': 4185, 'width': 120, 'y': 4135 },
        //     { 'type': 'VBandUpconverter', 'nodeName': 'udp单播', 'icon': 'tcpK', 'name': '1', 'id': 'commonc-33677bd993c84ec4a5d842901f0c6068', 'height': 50, 'x': 4185, 'width': 120, 'y': 4045 }
        //   ],
        //   'linkList': [],
        //   'attr': { 'id': 'flow-5' },
        //   'config':
        //     { 'showGrid': false, 'showGridText': '隐藏网格', 'showGridIcon': 'eye' },
        //   'status': '1',
        //   'remarks': []
        // }
        // this.loadFlow(JSON.stringify(data))
        getAction(this.url.find).then((response) => {
          if (response.success) {
            if (response.result.nodeList.length > 0) {
              response.result.nodeList.forEach((item) => {
                if (item.nodeName == '喇叭天线') {
                  item.icon = 'laBa'
                }
              })
            }
            this.loadFlow(JSON.stringify(response.result))

            // 测试数据
            // let flowData =
            //   '{"nodeList":[{"type":"controlEquipment","nodeName":"前端控制设备","icon":"udpOdd","id":"controlEquipment-f077bb20b3a745da886adb9fd406f20a","vmDeviceId":"166663885146344079372","height":50,"x":4515,"width":120,"y":4530},{"type":"exchangeBoard","nodeName":"交换机","icon":"udpMore","id":"exchangeBoard-6790fc0843b2422aadb4d17018406746","vmDeviceId":"1666682851463440793735","height":50,"x":4515,"width":120,"y":4405},{"type":"MeasurementControlBaseband","nodeName":"测控基带","icon":"NE40","id":"MeasurementControlBaseband-f14f0e1ecd9240ec8c7b26e9eef54ae3","vmDeviceId":"1666688514634407937","height":50,"x":5025,"width":120,"y":4420},{"type":"switchMatrix","nodeName":"中频开关矩阵","icon":"udpMore","id":"switchMatrix-44d4fec249b54d73958b9f4416ce3100","vmDeviceId":"1667064273336610818","height":50,"x":4515,"width":120,"y":4135},{"type":"singleChannelDownConverter","nodeName":"单通道下变频器","icon":"S5700","id":"singleChannelDownConverter-b3930bf1b27942faa75e849cc1c1a014","vmDeviceId":"1667746084362395649","height":50,"x":4920,"width":120,"y":4275},{"type":"QBandDownconverter","nodeName":"Q频段下变频器","icon":"USG5500","id":"QBandDownconverter-ea47e6bab34741e08e14c9acc7695c85","vmDeviceId":"1667049644824809474","height":50,"x":4380,"width":120,"y":4130},{"type":"VBandUpconverter","nodeName":"V频段上变频器","icon":"tcpK","id":"VBandUpconverter-d015e23529be4d4b83c2c3bc0080bb28","vmDeviceId":"1666688317829275649","height":50,"x":4180,"width":120,"y":4175},{"type":"ProtocolGateway","nodeName":"协议网关","icon":"tcpF","id":"ProtocolGateway-a60e4b69254542be8b25db8dc1bb2e27","vmDeviceId":"1666688172597305346","height":50,"x":4055,"width":120,"y":4300},{"type":"feedBaseband","nodeName":"馈电基带","icon":"udpOdd","id":"feedBaseband-ca7ceb15e0bd400786b5bea92ba8e029","vmDeviceId":"1666688011510865922","height":50,"x":4025,"width":120,"y":4420},{"type":"accessAuthentication","nodeName":"入网认证中心控制子系统","icon":"udpMore","id":"accessAuthentication-1f4e06899e3843838c7f702650200704","vmDeviceId":"16666885146344079224311735","height":50,"x":4515,"width":120,"y":4665},{"type":"VBandUpconverter","nodeName":"V频段上变频器","icon":"tcpK","id":"VBandUpconverter-5ace8bf00c5645d1a88bca12f3dd2828","vmDeviceId":"1666688317829275649","height":50,"x":4665,"width":120,"y":4135},{"type":"QBandDownconverter","nodeName":"Q频段下变频器","icon":"USG5500","id":"QBandDownconverter-b04d6056c2904f21b341944a384f01f5","vmDeviceId":"1667049644824809474","height":50,"x":4875,"width":120,"y":4190}],"linkList":[{"type":"link","id":"link-f22e6cf4d8dd4fbd8ec72df8bd23cc70","sourceId":"feedBaseband-ca7ceb15e0bd400786b5bea92ba8e029","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-7e021a46d3a6419684f8172f24a1a830","sourceId":"ProtocolGateway-a60e4b69254542be8b25db8dc1bb2e27","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-c4c7c667f54740e584fd7dedbf117591","sourceId":"QBandDownconverter-ea47e6bab34741e08e14c9acc7695c85","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-bcd55eabab764ca3b2a674a7ede15606","sourceId":"VBandUpconverter-d015e23529be4d4b83c2c3bc0080bb28","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-6a17ba63f7064ab880908720a0cac200","sourceId":"singleChannelDownConverter-b3930bf1b27942faa75e849cc1c1a014","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-f787afe92e8a46938e69ba2afa1549e0","sourceId":"switchMatrix-44d4fec249b54d73958b9f4416ce3100","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-d4c39c4dc6f140ab8cad89a8a340a9db","sourceId":"MeasurementControlBaseband-f14f0e1ecd9240ec8c7b26e9eef54ae3","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-b1538ea697c246fab18c64c381d06dff","sourceId":"controlEquipment-f077bb20b3a745da886adb9fd406f20a","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-108841b5356349d987d77ec96eb575dd","sourceId":"VBandUpconverter-5ace8bf00c5645d1a88bca12f3dd2828","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-c1e4eef237fa498d91c878b92c9e73f1","sourceId":"QBandDownconverter-b04d6056c2904f21b341944a384f01f5","targetId":"exchangeBoard-6790fc0843b2422aadb4d17018406746","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}},{"type":"link","id":"link-20427e1ac04b4efca86d38209bdb66a7","sourceId":"accessAuthentication-1f4e06899e3843838c7f702650200704","targetId":"controlEquipment-f077bb20b3a745da886adb9fd406f20a","label":"","cls":{"linkType":"Flowchart","linkColor":"#2a2929","linkThickness":2}}],"attr":{"id":""},"config":{"showGrid":false,"showGridText":"隐藏网格","showGridIcon":"eye"},"status":"2","remarks":[]}'
            // this.loadFlow(flowData)
          }
        })
      }
    },
    openWin() {
      this.deviceId = {}
      this.deviceId.isshow = true
      this.deviceId.sourceDeviceId = this.currentSelect.id
      this.visible = true
    },
    // 渲染流程
    loadFlow(json) {
      this.clear()
      this.$nextTick(() => {
        const loadData = JSON.parse(json)

        this.flowData.attr = loadData.attr
        this.flowData.config = loadData.config
        this.flowData.status = flowStatus.MODIFY
        this.plumb.batch(() => {
          const nodeList = loadData.nodeList
          nodeList.forEach((node) => {
            this.flowData.nodeList.push(node)
          })
          const linkList = loadData.linkList
          this.$nextTick(() => {
            if (linkList) {
              linkList.forEach((link, ild) => {
                const conn = this.plumb.connect({
                  source: link.sourceId,
                  target: link.targetId,
                  anchor: this.flowConfig.jsPlumbConfig.anchor.default,
                  connector: [
                    link.cls.linkType,
                    {
                      gap: 5,
                      cornerRadius: 8,
                      alwaysRespectStubs: true,
                    },
                  ],
                  paintStyle: {
                    stroke: link.cls.linkColor,
                    strokeWidth: link.cls.linkThickness,
                  },
                })
                const linkId = conn.id
                const labelHandle = (e) => {
                  const event = window.event || e
                  event.stopPropagation()
                  this.currentSelect = this.flowData.linkList.find((l) => l.id === linkId)
                }

                if (link.label !== '') {
                  conn.setLabel({
                    label: link.label,
                    cssClass: `linkLabel ${linkId}`,
                  })

                  // 添加label点击事件
                  document.querySelector('.' + linkId).addEventListener('click', labelHandle)
                } else {
                  if (document.querySelector('.' + linkId)) {
                    // 移除label点击事件
                    document.querySelector('.' + linkId).removeEventListener('click', labelHandle)
                  }
                }
              })
            }
            this.currentSelect = {}
            this.currentSelectGroup = []
            this.flowData.status = flowStatus.MODIFY
          })
        }, true)
        const canvasSize = this.computeCanvasSize()
        this.$refs.flowArea.container.pos = {
          top: -canvasSize.minY + 100,
          left: -canvasSize.minX + 100,
        }
        // 回显数据时关闭连线详情
        this.$nextTick(() => {
          this.visible = false
        })
      })
    },
    // 查找相关节点
    findNodeConfig(belongTo, type, callback) {
      let node = null
      switch (belongTo) {
        case 'commonNodes':
          node = commonNodes.find((n) => n.type === type)
          break
        case 'highNodes':
          node = highNodes.find((n) => n.type === type)
          break
        case 'laneNodes':
          node = laneNodes.find((n) => n.type === type)
          break
      }
      callback(node)
      // this.saveNodeInfo(this.flowData.nodeList.at(-1))
    },
    // 节点移动变化
    nodeInfo(node) {
      // this.saveNodeInfo(node)
    },
    // 保存节点
    saveNodeInfo(val) {
      const nodeObj = {
        ...val,
        deviceName: val.nodeName,
        instaId: this.flowChartData.id,
      }
      httpAction(this.url.saveNode, nodeObj, 'post').then((res) => {
        if (res.success) {
          this.flowData.nodeList.forEach((item) => {
            if (item.id === val.id) {
              item.deviceId = res.result.deviceId
            }
          })
        }
      })
    },
    // 设置工具
    selectTool(type) {
      const tool = tools.find((t) => t.type === type)
      if (tool) this.currentTool = tool

      switch (type) {
        case 'drag':
          this.changeToDrag()
          break
        case 'connection':
          this.changeToConnection()
          break
      }
    },
    // 切换为拖拽
    changeToDrag() {
      this.flowData.nodeList.forEach((node) => {
        console.log(this.plumb, 'this.plum')
        const f = this.plumb.toggleDraggable(node.id)
        if (!f) {
          this.plumb.toggleDraggable(node.id)
        }
        if (node.type !== 'x-lane' && node.type !== 'y-lane') {
          this.plumb.unmakeSource(node.id)
          this.plumb.unmakeTarget(node.id)
        }
      })
    },
    // 切换为连线
    changeToConnection() {
      this.flowData.nodeList.forEach((node) => {
        const f = this.plumb.toggleDraggable(node.id)
        if (f) {
          this.plumb.toggleDraggable(node.id)
        }
        if (node.type !== 'x-lane' && node.type !== 'y-lane') {
          this.plumb.makeSource(node.id, this.flowConfig.jsPlumbConfig.makeSourceConfig)
          this.plumb.makeTarget(node.id, this.flowConfig.jsPlumbConfig.makeTargetConfig)
        }
      })

      this.currentSelect = {}
      this.currentSelectGroup = []
    },
    // 切换为放大工具
    changeToZoomIn() {
      console.log('切换到放大工具')
    },
    // 切换为缩小工具
    changeToZoomOut() {
      console.log('切换到缩小工具')
    },
    // 检测流程数据有效性
    checkFlow() {
      const nodeList = this.flowData.nodeList

      if (nodeList.length <= 0) {
        this.$message.error('拓扑图中无任何节点！')
        return false
      }
      return true
    },
    // 保存流程
    saveFlow() {
      let obj = {}
      // 连接线每次重复绘制问题
      // this.flowData.linkList = this.flowData.linkList.reduce((curr, next) => {
      //   // 判断对象中是否已经有该属性  没有的话 push 到 curr数组
      //   obj[next.sourceId + next.targetId] ? '' : obj[next.sourceId + next.targetId] = curr.push(next)
      //   return curr
      // }, [])
      const flowObj = Object.assign({}, this.flowData)
      if (!this.checkFlow()) return
      flowObj.status = flowStatus.SAVE
      // flowObj.linkList.filter(x=>x.sourceId)
      const d = JSON.stringify(flowObj)
      httpAction('/topology/saveTopology', flowObj, 'post').then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.initFlow()
        } else {
          this.$message.error(res.message)
        }
      })
      return d
    },
    // 生成拓扑图片
    exportFlowPicture() {
      if (!this.checkFlow()) return

      const $Container = this.$refs.flowArea.$el.children[0]
      const svgElems = $Container.querySelectorAll('svg[id^="link-"]')
      const removeArr = []

      svgElems.forEach((svgElem) => {
        const linkCanvas = document.createElement('canvas')
        const canvasId = 'linkCanvas-' + utils.getId()
        linkCanvas.id = canvasId
        removeArr.push(canvasId)

        const svgContent = svgElem.outerHTML.trim()
        canvg(linkCanvas, svgContent)
        if (svgElem.style.position) {
          linkCanvas.style.position += svgElem.style.position
          linkCanvas.style.left += svgElem.style.left
          linkCanvas.style.top += svgElem.style.top
        }
        $Container.appendChild(linkCanvas)
      })

      const canvasSize = this.computeCanvasSize()

      const pbd = this.flowConfig.defaultStyle.photoBlankDistance
      const offsetPbd = utils.div(pbd, 2)

      html2canvas($Container, {
        width: canvasSize.width + pbd,
        height: canvasSize.height + pbd,
        scrollX: -canvasSize.minX + offsetPbd,
        scrollY: -canvasSize.minY + offsetPbd,
        logging: false,
        onclone: () => {
          removeArr.forEach((id) => {
            const currentNode = document.querySelector('#' + id)
            currentNode.parentNode.removeChild(currentNode)
          })
        },
      }).then((canvas) => {
        const dataURL = canvas.toDataURL('image/png')
        this.flowPicture.url = dataURL
        this.flowPicture.modalVisible = true
      })
    },
    // 下载图片
    downLoadFlowPicture() {
      const alink = document.createElement('a')
      const alinkId = 'alink-' + utils.getId()
      alink.id = alinkId
      alink.href = this.flowPicture.url
      alink.download = '流程设计图_' + this.flowData.attr.id + '.png'
      alink.click()
    },
    // 取消下载
    cancelDownLoadFlowPicture() {
      this.flowPicture.url = ''
      this.flowPicture.modalVisible = false
    },
    // 计算拓扑图宽高
    computeCanvasSize() {
      const nodeList = Object.assign([], this.flowData.nodeList)
      let minX = nodeList[0].x
      let minY = nodeList[0].y
      let maxX = nodeList[0].x + nodeList[0].width
      let maxY = nodeList[0].y + nodeList[0].height

      nodeList.forEach((node) => {
        minX = Math.min(minX, node.x)
        minY = Math.min(minY, node.y)
        maxX = Math.max(maxX, node.x + node.width)
        maxY = Math.max(maxY, node.y + node.height)
      })
      const canvasWidth = maxX - minX
      const canvasHeight = maxY - minY
      return {
        width: canvasWidth,
        height: canvasHeight,
        minX: minX,
        minY: minY,
        maxX: maxX,
        maxY: maxY,
      }
    },
    // 清除画布
    clear() {
      this.flowData.nodeList.forEach((node) => {
        this.plumb.remove(node.id)
      })
      this.currentSelect = {}
      this.currentSelectGroup = []
      this.flowData.nodeList = []
      this.flowData.linkList = []
      this.flowData.remarks = []
    },
    // 显示隐藏网格
    toggleShowGrid() {
      const flag = this.flowData.config.showGrid
      if (flag) {
        this.flowData.config.showGrid = false
        this.flowData.config.showGridText = '显示网格'
        this.flowData.config.showGridIcon = 'eye-invisible'
      } else {
        this.flowData.config.showGrid = true
        this.flowData.config.showGridText = '隐藏网格'
        this.flowData.config.showGridIcon = 'eye'
      }
    },
    hinddenSider() {
      this.areaName = !this.areaName
    },
    // toggleClass(el, class_name) {
    //   let class_list = el.className,
    //     class_list_arr = class_list.split(' ')
    //   //如果要兼容IE8以下，这个判断地方改成传统循环就行
    //   if (
    //     class_list_arr.some(function (item, i, arr) {
    //       return item === class_name
    //     })
    //   ) {
    //     //删除
    //     for (let i = 0; i < class_list_arr.length; i++) {
    //       //如果有相同的类，则删除，否则不予理会
    //       if (class_list_arr[i] === class_name) {
    //         class_list_arr.splice(i, 1)
    //         break //找到就跳出循环，减少消耗
    //       }
    //     }
    //   } else {
    //     //添加
    //     class_list_arr.push(class_name)
    //   }
    //   el.className = class_list_arr.join(' ')
    // },
    // 设置
    setting() {
      this.$refs.settingModal.open()
    },
    // 快捷键大全
    shortcutHelper() {
      this.$refs.shortcutModal.open()
    },
    // 使用文档
    goGit() {
      window.open(this.info.gitee)
    },
    // 连接线右键
    showLinkContextMenu(e) {
      const event = window.event || e
      event.preventDefault()
      event.stopPropagation()
      document.querySelector('.vue-contextmenuName-flow-menu').style.display = 'none'
      document.querySelector('.vue-contextmenuName-node-menu').style.display = 'none'
      const x = event.clientX
      const y = event.clientY
      this.linkContextMenuData.axis = { x, y }
    },
    // 查看线
    viewLink() {
      this.deviceId = {}
      this.deviceId.isshow = true
      this.deviceId.devSourId = this.flowData.nodeList.find((item) => item.id === this.currentSelect.sourceId).deviceId
      this.deviceId.devTargId = this.flowData.nodeList.find((item) => item.id === this.currentSelect.targetId).deviceId
      this.deviceId.id = this.currentSelect.id
      this.deviceId.portObj = this.flowData.linkList.find((item) => item.id === this.currentSelect.id)
      this.visible = true
    },
    // 删除线
    deleteLink() {
      deleteAction(this.url.deleteLine, { id: this.currentSelect.id }).then((res) => {
        // if (res.success) {
        //   this.$message.success('删除连线成功')
        // } else {
        //   this.$message.error(res.message)
        // }
      })

      this.plumb.deleteConnection(
        this.plumb.getConnections({
          source: this.currentSelect.sourceId,
          target: this.currentSelect.targetId,
        })[0]
      )

      const linkList = this.flowData.linkList
      this.flowData.linkList.splice(
        linkList.findIndex(
          (link) => link.sourceId === this.currentSelect.sourceId && link.targetId === this.currentSelect.targetId
        ),
        1
      )
      this.currentSelect = {}
    },
    // 设置快捷键失效
    loseShortcut() {
      this.activeShortcut = false
    },
    // 设置快捷键启用
    getShortcut() {
      this.activeShortcut = true
    },
    // 测试
    openTest() {
      const flowObj = Object.assign({}, this.flowData)
      this.$refs.testModal.flowData = flowObj
      this.$refs.testModal.testVisible = true
    },
    // 键盘移动节点
    moveNode(type) {
      let m = this.flowConfig.defaultStyle.movePx
      let isX = true

      switch (type) {
        case 'left':
          m = -m
          break
        case 'up':
          m = -m
          isX = false
          break
        case 'right':
          break
        case 'down':
          isX = false
      }

      if (this.currentSelectGroup.length > 0) {
        this.currentSelectGroup.forEach((node) => {
          if (isX) {
            node.x += m
          } else {
            node.y += m
          }
        })
        this.plumb.repaintEverything()
      } else if (this.currentSelect.id) {
        if (isX) {
          this.currentSelect.x += m
        } else {
          this.currentSelect.y += m
        }
        this.plumb.repaintEverything()
      }
    },
  },
}
</script>
<style scoped>
::v-deep .textStyle {
  margin-bottom: 20px;

  transform: translate(-10%, -90%) !important;
}

.content-right {
  margin-left: 30px;
  margin-right: 10px;
  border: 1px solid rgba(144, 147, 153, 0.3);
  border-radius: 5px;
  background: #fafafa;
  /* flex: 0 0 100px !important; */
  max-width: 580px !important;
  min-width: 580px !important;
  width: 580px !important;
}
.content{
  position: relative;
}
.container .ant-layout {
  width: 100%;
  height: 100%;
}
.container .ant-layout  #conten-box{
    width: 100% !important;
}
</style>
